package vip.xiaonuo.modular.manage.tsdatarecord.parser;

import cn.hutool.core.io.IoUtil;
import com.alibaba.excel.EasyExcel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.modular.file.util.CommonFileUtils;
import vip.xiaonuo.modular.manage.tsdatarecord.entity.BaseMetadata;
import vip.xiaonuo.modular.manage.tsdatarecord.enums.FileParseExceptionEnum;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.List;
import java.util.function.Consumer;

/**
 * ExcelFileParser
 *
 * @author JackLee
 * 2022/8/5 16:00
 */
@Component
@Slf4j
public class ExcelFileParser implements FileParser {
    @Override
    public boolean available(String extension) {
        return StringUtils.equalsAny(extension, CommonFileUtils.FileType.XLS, CommonFileUtils.FileType.XLSX);
    }

    @Override
    public ParserResult parse(String filePath, Integer dealSize, String recordId, Consumer<List<BaseMetadata>> consumer) {
        FileInputStream inputStream = null;
        ParserResult parserResult = new ParserResult();
        try {
            inputStream = new FileInputStream(filePath);
            EasyExcel.read(inputStream, new ExcelDataListener(dealSize, recordId, consumer, parserResult)).headRowNumber(1).sheet().doRead();
            log.info("{}文件解析完成！", filePath);
            return parserResult;
        } catch (FileNotFoundException e) {
            log.error("文件不存在：{}", filePath);
            throw new ServiceException(FileParseExceptionEnum.NOT_EXIST);
        } finally {
            IoUtil.close(inputStream);
        }
    }

}
